<template>
    <div class="lineWork_takePhoto_div" v-loading="loading">
        <div class="LW_takePhoto_div">
            <a-button type="primary" class="LW_takePhoto_button" @click="takePhotoBySelect">拍照</a-button>
        </div>
        <div class="LW_jump_div">
            <a-button type="primary" class="LW_jump_button" @click="showModal_jump">跳过</a-button>
            <a-modal title="请选择跳过原因:" v-model="visible_jump" @ok="handleOk_jump" cancelText="取消" okText="确认" >
                <select  name="jump_state" class="LW_jump_select" id="LW_jump_select" v-model="jumpSelected" >
                    <option :value="jump.name" v-for="jump in jumpList">{{jump.name}}</option>
                </select>
            </a-modal>
        </div>
        <!--<div class="LW_stop_div">
            <a-button type="primary" class="LW_stop_button" @click="showModal_stop">终止</a-button>
            <a-modal title="请选择终止原因:" v-model="visible_stop" @ok="handleOk_stop" cancelText="取消" okText="确认">
                <select  name="stop_state" class="LW_jump_select" id="LW_stop_select" v-model="stopSelected" >
                    <option :value="stop.name" v-for="stop in stopList">{{stop.name}}</option>
                </select>
            </a-modal>
        </div>-->
    </div>
</template>
<style >
.lineWork_takePhoto_div{
    width: 100vw;
    text-align: center;
    padding-top: 30vw;
}

.LW_takePhoto_div {
    width: 100vw;
    height: 35vw;
}
.LW_takePhoto_button {
    width: 50vw;
    height: 35vw;
    background: rgb(74, 184, 244);
    border: 0.3vw solid rgb(74, 184, 244);
    border-radius: 5vw;
    font-size:10vw;
}
.LW_jump_div {
    width: 100vw;
    height: 25vw;
    margin: 10vw 0 10vw 0;
}
.LW_jump_button {
    width: 40vw;
    height: 25vw;
    background: rgb(74, 184, 244);
    border: 0.3vw solid rgb(74, 184, 244);
    border-radius: 5vw;
    font-size:8vw;
}

.LW_stop_div {
    width: 100vw;
    height: 25vw;
}
.LW_stop_button {
    width: 40vw;
    height: 25vw;
    background: rgb(74, 184, 244);
    border: 0.3vw solid rgb(74, 184, 244);
    border-radius: 5vw;
    font-size:8vw;
}
    .LW_jump_select{
        width: 80vw;
        background: lightgray;
        font-size: 5vw;
        height: 12vw;
        outline:none;
    }
.LW_stop_select{
    width: 80vw;
    background: lightgray;
    font-size: 5vw;
    height: 12vw;
    outline:none;
}
</style>
<script>
    import Options from "ant-design-vue/es/vc-pagination/Options";
    import axios from 'axios';
    export default {
        name: "LineWorkTakePhoto",
        components: {Options},
        created(){
            this.jumpSelected = this.jumpList[0].name;
            this.stopSelected = this.stopList[0].name;
        },
        mounted(){
            this.getStep();
        },
        data() {
            return {
                visible_jump: false,
                visible_stop:false,
                step:'',
               /* step:this.$route.params.step,*/
                lineWorkUrl:'',
                jumpSelected:'',
                stopSelected:'',
                jumpList:[
                        {
                            value: '1',
                            name: '个人原因跳过'
                        },
                        {
                            value: '2',
                            name: '计划场景不符合跳过'
                        },
                        {
                            value: '3',
                            name: '拍照设备跳过'
                        },
                ],
                stopList:[
                    {
                        value: '1',
                        name: '个人原因终止'
                    },
                    {
                        value: '2',
                        name: '计划场景不符合终止'
                    },
                    {
                        value: '3',
                        name: '拍照设备损坏终止'
                    },
                ],
                id:'',
                name:'',
                sid:localStorage.getItem("sid"),
                workModeId:localStorage.getItem("workModeId"),
                Authorization:localStorage.getItem("userToken"),
                fileName:'',
                createTime:'',
                myPhotoInfo:{},
                reportHistory:localStorage.getItem("reportHistory")?JSON.parse(localStorage.getItem("reportHistory")):[],
                latitude:localStorage.getItem("latitude")?localStorage.getItem("latitude"):"",
                longitude:localStorage.getItem("longitude")?localStorage.getItem("longitude"):"",
                loading: false,
                gis4_imei:localStorage.getItem("gis4_imei"),
                gis4_phone:localStorage.getItem("gis4_phone"),
                fileList:[],
                myFileName:'',
                fileURL:'',
            }
        },
        methods:{
            showModal_jump(){
                 this.visible_jump = true;
                },
            handleOk_jump(e) {
                this.visible_jump = false;
                let that = this;
                let name = that.name;//当前步骤
                let methodName = "跳过";//开始 确认 跳过
                let note = that.jumpSelected;
                that.$api.step(that.id,name,methodName,note).then((resp)=>{
                    if(resp.status === 200){
                        //let otherFailSendInfo = failSendInfo.filter(item=>item.UserId!==UserId);//其余的失败信息集合*/
                        console.log("计划跳过成功");
                        that.$router.push({name:this.lineWorkUrl,params: {step:that.step,name:that.name,id:that.id}});
                    }
                }).catch((error)=>{
                    that.$alert("计划跳过失败");
                    console.log(error);
                });
            },
            showModal_stop(){
                this.visible_stop = true
            },
            handleOk_stop(e) {
                this.visible_stop = false;
                this.$router.push({name:this.lineWorkUrl});
                console.log(this.lineWorkUrl);
            },
            getStep(){
                this.step = this.$route.params.step?this.$route.params.step:JSON.parse(localStorage.getItem("currStepInfo")).step;
                this.id = this.$route.params.id?this.$route.params.id:JSON.parse(localStorage.getItem("currStepInfo")).id;
                this.name = this.$route.params.name?this.$route.params.name:JSON.parse(localStorage.getItem("currStepInfo")).name;
                console.log("this step is:"+this.step+" planName:"+this.name+" planId:"+this.id);
                let n = parseInt(this.step);
                switch(n)
                {
                    //这里的n代表下一步的路由
                    case 1:
                        this.lineWorkUrl = 'lineWorkSurePerson';
                        break;
                    case 2:
                        this.lineWorkUrl = 'lineWorkSureTool';
                        break
                    case 3:
                        this.lineWorkUrl = 'lineWorkInto';
                        break;
                    case 4:
                        this.lineWorkUrl = 'lineWorkBegin';
                        break;
                    case 5:
                        this.lineWorkUrl = 'lineWorkEnd';//结束作业
                        break;
                    case 6:
                        this.lineWorkUrl = 'lineWorkOut';//跳过7作业工单,到8作业出场
                        break;
                    case 8:
                        this.lineWorkUrl = 'lineWorkSureOutTool';//9确认料具出
                        break;
                    case 9:
                        this.lineWorkUrl = 'lineWorkReturn';
                        break;
                    default:
                        this.lineWorkUrl = 'lineWork';
                        break;
                }
            },
            takePhoto(){
                //原来的拍照方法，mediaCamera插件，得到base64，转blob,再转文件，拍一张上传一张
                /*let me = this;*/
                let cameraOptions= {
                    quality : 100,
                    destinationType : Camera.DestinationType.DATA_URL,
                    sourceType : Camera.PictureSourceType.CAMERA,     //照相机类型
                    allowEdit : false,
                    encodingType : Camera.EncodingType.JPEG,
                    /*targetWidth : 100,
                    targetHeight : 100,*/
                    SaveToPhotoAlburn:true,//捕获后将图像保存到设备上的相册中。
                    popoverOptions : CameraPopoverOptions,
                    saveToPhotoAlbum : true,
                    correctOrientation: true,
                };
                console.log("调用拍照接口");
                navigator.camera.getPicture(this.onCameraSuccess,this.onCameraError,cameraOptions);
            },
            onCameraSuccess(imageURL){
                let nowTime = new Date();
                console.log("takePhotoSuccess:");
                /*this.isShow = true ;*/
                /*this.imgUrl = imageURL ;*/
                this.sendStep(imageURL,nowTime);//发送当前步骤信息，并出现确认是否继续拍照
                this.addTaskToast();//后台上传中
                /*this.sendPhoto(imageURL,nowTime);*/

            },
            onCameraError(e){
                console.log("onCameraError:" + e);
            },
            sendPhoto(imageURL,nowTime) {
                let formData = new FormData();

                let getBlob = this.convertBase64UrlToBlob(imageURL);
                let file = this.blobToFile(getBlob);
                this.fileName = this.getFileTime(nowTime)+".jpg";
                this.createTime = this.getFormatTimeLine(nowTime);

                formData.append("file",file,this.fileName);
                formData.append('WorkStep',this.name);
                formData.append('WorkPlanId',this.id);
                formData.append('userId',this.sid);
                formData.append('workModeId',this.workModeId);
                formData.append("longitude",this.longitude);
                formData.append("latitude",this.latitude);
                formData.append("time",this.createTime);
                /*formData.append("file",this.convertBase64UrlToBlob(imageURL));*/

                console.log(file);
                console.log(formData.get('file'));
                let configs = {
                    headers: {
                        "Content-Type":'multipart/form-data',
                        "Authorization":this.Authorization,
                        "gis4_imei":this.gis4_imei,
                        "gis4_time":new Date().getTime(),
                        "gis4_phone":this.gis4_phone,
                        "WorkPlanNo":me.$store.state.planNo,
                        "gis4_longitude":localStorage.getItem("longitude"),
                        "gis4_latitude": localStorage.getItem('latitude'),
                        "version" : localStorage.getItem('version'),
                        "gis4_workmode" :localStorage.getItem('workModeId'),


                    }
                   /* ,timeout:3000*/
                };
                axios.post('http://'+localStorage.getItem("apiHost")+'/app/work/upload',formData,configs).then(res=>{
                    if(res.status === 200){
                        this.myPhotoInfo.fileName = this.fileName;
                        this.myPhotoInfo.createTime = this.createTime;
                        this.myPhotoInfo.sid = this.sid;
                        this.reportHistory.push(this.myPhotoInfo);
                        this.myPhotoInfo.isOk = "1";
                        localStorage.setItem("reportHistory",JSON.stringify(this.reportHistory));//保存进内存
                        console.log("照片上传成功");
                        /*this.addTaskToast();
                        this.sendStep();*/
                    }
                }).catch((error) =>{
                    console.log("照片信息提交失败");
                    console.log(error);
                    this.myPhotoInfo.fileName = this.fileName;
                    this.myPhotoInfo.createTime = this.createTime;
                    this.myPhotoInfo.sid = this.sid;
                    this.reportHistory.push(this.myPhotoInfo);
                    this.myPhotoInfo.isOk = "0";
                    localStorage.setItem("reportHistory",JSON.stringify(this.reportHistory));//保存进内存
                    this.sendPhotoFaileToast();


            })
            },

            convertBase64UrlToBlob(imageURI) {
                let bytes = window.atob(imageURI); //去掉url的头，并转换为byte
                //处理异常,将ascii码小于0的转换为大于0
                let ab = new ArrayBuffer(bytes.length);
                let ia = new Uint8Array(ab);
                for(let i = 0; i < bytes.length; i++) {
                    ia[i] = bytes.charCodeAt(i);
                }
                return new Blob([ab], { type: 'image/jpeg' });
            },
            blobToFile(theBlob,fileName) {
                //将blob转换为file
                theBlob.lastModifiedDate = new Date();
                theBlob.name = fileName;
                return theBlob;
            },
            getFileTime(nowTime){
                let year = nowTime.getFullYear();
                let mouth = nowTime.getMonth() + 1;
                let day =nowTime.getDate();
                let hour = nowTime.getHours();
                let minutes = nowTime.getMinutes();
                let seconds= nowTime.getSeconds();

                //将时分秒转化为双位数
                let mouth1 =setNum(mouth);
                let day1 =setNum(day);
                let h1 = setNum(hour);
                let m1 = setNum(minutes);
                let s1 = setNum(seconds);

                //输出时分秒
                let fileName = year+mouth1+day1+h1+m1+s1;
                //设置函数 把小于10的数字转换为两位数
                function setNum(num){ return num < 10 ? '0' + num : num }
                return fileName;

            },
            getFormatTimeLine(nowTime){
                //获取一个现在的时间
                let year = nowTime.getFullYear();
                let mouth = nowTime.getMonth() + 1;
                let day =nowTime.getDate();
                let hour = nowTime.getHours();
                let minutes = nowTime.getMinutes();
                let seconds= nowTime.getSeconds();

                //将时分秒转化为双位数
                let mouth1 =setNum(mouth);
                let day1 =setNum(day);
                let h1 = setNum(hour);
                let m1 = setNum(minutes);
                let s1 = setNum(seconds);

                //输出时分秒
                let createTime = year+"-"+mouth1+"-"+day1+" "+h1+":"+m1+":"+s1;
                //设置函数 把小于10的数字转换为两位数

                function setNum(num){ return num < 10 ? '0' + num : num }
                return createTime;

            },
            sendStep(imageURL,nowTime){
                let that = this;
                let methodName = "确认";
                let note = '';
                that.$api.step(that.id,that.name,methodName,note).then((resp)=>{
                    if(resp.status === 200){
                        //let otherFailSendInfo = failSendInfo.filter(item=>item.UserId!==UserId);//其余的失败信息集合*/
                        console.log("计划确认成功");
                        /*that.$router.push({name:this.lineWorkUrl,params: {step:that.step,id:that.id}});*/
                        that.$router.push({name:'lineWorkSurePhoto',params: {lineWorkUrl:that.lineWorkUrl,step:that.step,id:that.id,name:that.name}});
                    }
                }).catch((error)=>{
                    console.log(error);
                    alert("计划流程出错");
                });
                that.loading = true;
                that.sendPhoto(imageURL,nowTime);
            },
            sendStepBySelect(){
                let that = this;
                let methodName = "确认";
                let note = '';
                that.$api.step(that.id,that.name,methodName,note).then((resp)=>{
                    if(resp.status === 200){
                        //let otherFailSendInfo = failSendInfo.filter(item=>item.UserId!==UserId);//其余的失败信息集合*/
                        console.log("计划确认成功");
                        //that.$router.push({name:that.lineWorkUrl,params: {lineWorkUrl:that.lineWorkUrl,step:that.step,id:that.id,name:that.name}});
                        that.$router.push({name:this.lineWorkUrl,params: {step:that.step,id:that.id}});
                    }
                }).catch((error)=>{
                    console.log(error);
                    that.$alert("计划流程出错");
                });

            },
            addTaskToast() {
                window.plugins.toast.showWithOptions(
                    {
                        message: "后台上传中...",
                        duration: "short", // which is 2000 ms. "long" is 4000. Or specify the nr of ms yourself.
                        position: "bottom",
                        addPixelsY: -60  // added a negative value to move it up a bit (default 0)
                    },
                    function(){console.log('toast success: ')},
                    function(){console.log('toast error: ')}
                );
            },
            sendPhotoFaileToast() {
                window.plugins.toast.showWithOptions(
                    {
                        message: "线路作业照片上传失败",
                        duration: "short", // which is 2000 ms. "long" is 4000. Or specify the nr of ms yourself.
                        position: "bottom",
                        addPixelsY: -40  // added a negative value to move it up a bit (default 0)
                    },
                    function(){console.log('sendPhotoFaileToast Toast toast success:')},
                    function(){console.log('toast error: ')}
                );
            },
            sendPhotoOkToast() {
                window.plugins.toast.showWithOptions(
                    {
                        message: "线路作业照片上传成功",
                        duration: "short", // which is 2000 ms. "long" is 4000. Or specify the nr of ms yourself.
                        position: "bottom",
                        addPixelsY: -40  // added a negative value to move it up a bit (default 0)
                    },
                    function(){console.log('sendPhotoOkToast success:')},
                    function(){console.log('toast error: ')}

                );
            },
            takePhotoBySelect(){
                let me = this;
                console.log('我要拍摄线路作业图片');
                me.fileList = [] ;//清空图片文件列表
                let success = function (result) {
                    console.log("拍摄线路作业图片成功", result);
                    if (result.length > 0) {
                        me.sureContinue();//确认是否继续拍照上传还是进入下一步骤
                        let nowTime = new Date();
                        me.createTime = me.getFormatTimeLine(nowTime);
                        //返回的数据一个为jsonArray，一个图片有未压缩地址filePath和压缩地址compressPath，循环得乘以2
                        for(let i = 0;i<(result.length)/2;i++){
                            me.fileURL = result[2*i+1];//这里取压缩地址，未压缩地址为：result[2*i]
                            let arrName = result[2*i+1].split("/");
                            me.myFileName = arrName[(arrName.length) - 1];
                            me.fileList.push({fileURL:me.fileURL,fileName:me.myFileName,progress:0,isUploadOk:''});
                            me.changeTypeAndUpload();//立即上传
                        }

                        /*
                        //百度定位请求经纬度信息
                        let nowTime = new Date();
                        me.createTime = me.getFormatTimeLine(nowTime);
                        me.$getBaiduLocation().then(result => {
                            me.latitude = result.latitude;
                            me.longitude = result.longitude;
                        }).catch(error => {
                            //me.$store.commit('hideLoading');
                            console.log("getCooUsingBaiduSdk error:",error);
                            me.$alert("定位信息未获取");
                            return ;
                        });*/
                    }

                };
                let fail = function (error) {
                    console.log("拍摄图片失败", error);
                    me.$alert("拍照出现异常");
                };
                myMediaPlugin.takeImage(success, fail, {});
            },
            sureContinue(){
                let me = this;
                let title = "拍照选择";
                let message = "还要拍照？";
                let buttonLabels = ["继续拍照","下一步骤"];//出现界面：2取消 1确认
                navigator.notification.confirm(message, confirmCallback, title, buttonLabels);
                function confirmCallback(buttonIndex) {
                    if(buttonIndex===1){
                        console.log("You clicked right button 继续拍照" + buttonIndex);
                        me.takePhotoBySelect();//继续拍照
                    }else if(buttonIndex===2){
                        console.log("You clicked left button 下一步骤" + buttonIndex);
                        me.sendStepBySelect();//下一步骤

                    }else{
                        console.log("You clicked left button" + buttonIndex);
                        me.sureContinue();
                    }
                }
            },
            changeTypeAndUpload(){
                //通过自定义图片选择器，得到图片压缩/未压缩路径，然后lrz再压缩得到实体文件
                //获取经纬度
                //formData上传
                let me = this;
                me.addTaskToast();
                for(let i = 0;i<me.fileList.length;i++){
                    console.log(me.fileList[i].fileURL);
                    lrz( me.fileList[i].fileURL, {width:1080,height:1920,quality:0.6}).then(function(rst) {

                        let file = rst.file;
                        let formData = new FormData();
                        formData.append("file",file,me.fileList[i].fileName);//me.myFileName
                        formData.append('LongitudeGcj02',localStorage.getItem("longitude"));
                        formData.append('LatitudeGcj02',localStorage.getItem("latitude"));
                        formData.append('userId',me.sid);
                        formData.append('workModeId',me.workModeId);
                        formData.append("time",me.createTime);
                        formData.append("WorkStep",me.name);
                        formData.append("WorkPlanId",me.id);
                        let configs = {
                            headers: {
                                "Content-Type":'multipart/form-data',
                                "Authorization":me.Authorization,
                                "gis4_imei":me.gis4_imei,
                                "gis4_time":me.createTime,
                                "gis4_phone":me.gis4_phone,
                                "WorkPlanNo":me.$store.state.planNo,
                                "gis4_longitude":localStorage.getItem("longitude"),
                                "gis4_latitude": localStorage.getItem('latitude'),
                                "version" : localStorage.getItem('version'),
                                "gis4_workmode" :localStorage.getItem('workModeId'),

                            },

                        };
                        axios.post('http://'+localStorage.getItem("apiHost")+'/app/work/upload',formData,configs).then(res=> {
                            if(res.status === 200){
                                me.myPhotoInfo.fileName = me.fileList[i].fileName;
                                me.myPhotoInfo.createTime = me.createTime;
                                me.myPhotoInfo.isOk = "1";
                                me.myPhotoInfo.sid = me.sid;
                                me.reportHistory.push(me.myPhotoInfo);
                                me.isOk = "1";
                                me.fileList[i].isUploadOk = true;
                                me.sendPhotoOkToast();
                                localStorage.setItem("reportHistory",JSON.stringify(me.reportHistory));//保存进内存

                            }
                        }).catch((error) =>{
                            console.log("照片信息提交失败");
                            console.log(error);
                            me.myPhotoInfo.fileName = me.fileList[i].fileName;
                            me.myPhotoInfo.createTime = me.createTime;
                            me.myPhotoInfo.isOk = "0";
                            me.myPhotoInfo.sid = me.sid;
                            me.reportHistory.push(me.myPhotoInfo);
                            me.isOk = "0";
                            me.fileList[i].isUploadOk = false;
                            me.sendPhotoFaileToast();
                            localStorage.setItem("reportHistory",JSON.stringify(me.reportHistory));//保存进内存
                        })
                    }).catch(function(error) {
                        //失败时执行
                        console.log(error);
                        me.fileList[i].isUploadOk = false;
                        me.$alert("lrz转换文件失败");
                    }).always(function() {
                        //不管成功或失败，都会执行
                    });
                }


            },

        },
    }
</script>

